const BASE_URL_MAP = {
	DEV: "http://localhost:8200",
};

function getResult(resp) {
	const {
		data
	} = resp.data;
	const result = data || resp;
	return result;
}

/**
 * 接口请求
 * @param url 接口地址
 * @param method 请求方法 [get,post,put]
 * @param data 参数
 */
async function request(uri, options = {}) {
	let header = {
		...(options.header || {}),
	};
	header = handleHeader(header);
	const method = options.method || "get";
	if (method == "post") {
		header["content-type"] = "application/json";
	}
	let data = options.data;
	const url = BASE_URL_MAP.DEV + uri;
	if (options.showLoad) {
		uni.showLoading({
			title: "加载中...",
			// mask:true
		});
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method: options.method,
			data: data,
			header,
			success(resp) {
				const {
					statusCode
				} = resp;
				if (statusCode === 200) {
					return handleSuccess(resp, resolve);
				}
				return handleFail(resp, reject);
			}
		});
	});
};


function handleSuccess(resp, resolve) {
	const result = getResult(resp);
	return resolve(result);
}

function handleFail(resp, reject) {
	const {
		statusCode,
		data
	} = resp;
	if (statusCode === 401) {
		uni.removeStorageSync('token')
		uni.navigateTo({
			url: '/pages/login/login'
		})
	} else {
		uni.showModal({
			title: "操作失败",
			content: data
		})
	}
	return reject(resp);
}



function handleHeader(header) {
	const token = uni.getStorageSync("token");
	if (token) {
		header.token = token;
	}
	return header;
}


export default request;